package com.xuanwu.ai.flow.component;

import com.alibaba.fastjson.JSONObject;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.dto.CmpDataDTO;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.sao.AIDetectSao;
import com.xuanwu.ai.flow.sao.req.BlurDetectReq;
import com.xuanwu.ai.flow.utils.NodeDataUtils;
import com.xuanwu.ai.web.exception.BizException;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeIfComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 模糊识别条件组件
 */
@LiteflowComponent(name = "模糊识别条件组件", value = "blurDetectIFCmp")
@Slf4j
public class BlurDetectIFCmp extends NodeIfComponent {

    @Autowired
    private AIDetectSao aiDetectSao;

    @Override
    public boolean processIf() {
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);
        if (customContext.getToken() == null) {
            throw new BizException(ErrorCodeEnum.NO_VALID_TOKEN);
        }
        BlurDetectReq blurDetectReq = new BlurDetectReq();
        blurDetectReq.setUrl(customContext.getUrl());
        JSONObject jsonObject = aiDetectSao.blurDetect(customContext.getToken(), blurDetectReq);
        log.info("模糊识别结果:{}", jsonObject.getJSONObject("data"));
        // 设置节点数据
        NodeDataUtils.setStepNodeData(customContext, this.getCmpData(CmpDataDTO.class).getUuid(), this.getName(), jsonObject);

        if(jsonObject.getInteger("status").equals(GlobalConstant.CMP_EXECUTE_FAIL)){
            throw new BizException(ErrorCodeEnum.CMP_EXECUTE_FAIL, this.getName());
        }

        return GlobalConstant.IS_BLUR_PHOTO.compareTo(jsonObject.getJSONObject("data").getBigDecimal("blur")) > -1;
    }
}
